<template>
  <div class="follow-list" ref="pageRef" @scroll="handleScroll">
    <template v-if="tableData.length === 0 && finish">
      <div class="empty">
        <n-empty size="large" description="暂无数据~"></n-empty>
      </div>
    </template>
    <template v-else>
      <div class="cell" v-for="item in tableData" :key="item.id">
        <div class="user-card">
          <div class="cursor-pointer" @click="handDetail(item)">
            <n-avatar round :size="avatarSize" :src="item.avatar" />
          </div>
          <div class="name cursor-pointer" @click="handDetail(item)">
            {{ item.nickname }}
          </div>
          <!-- <div class="desc u-line-1">{{ item.job }}</div> -->
          <div class="more">
            <span>作品 {{ item.gz_work_count }}</span>
            <span>粉丝 {{ item.fans_count }}</span>
          </div>
          <template v-if="item.isFollow">
            <n-button
              style="--n-border: none"
              class="follw-btn"
              @click.stop="handCancel(item)"
            >
              <span v-if="item.isByFansConcern">互相关注</span>
              <span v-else>已关注</span>
            </n-button>
          </template>
          <template v-else>
            <n-button
              type="primary"
              style="--n-border: none"
              class="btn"
              @click.stop="handCancel(item)"
            >
              <i class="landscape landscape-jia"></i>
              <span>关注</span>
            </n-button>
          </template>
        </div>
        <img
          v-for="(el, n) in item.childer"
          :key="n"
          class="hor-img"
          :src="el.cover"
          @click.stop="handContentDetail(el)"
          alt=""
        />
      </div>
    </template>
    <confirm-dia ref="confirmRef" :title="tips" @confirm="handConfirm" />
  </div>
</template>
<script setup lang="ts">
import { NAvatar, NButton, NEmpty, useMessage } from 'naive-ui'
import { useWindowSize } from '@vueuse/core/index'
import { computed, defineAsyncComponent, inject, onMounted, ref } from 'vue'
import homeApi from '@/service/api/home'
import followApi from '@/service/api/follow'
import { useAppsStore } from '@/stores/modules/app'
import { storeToRefs } from 'pinia'
import { useRouter } from 'vue-router'
type PropsState = {
  userId: number
}
const props = withDefaults(defineProps<PropsState>(), {
  userId: 0
})
const emit = defineEmits(['change'])
const useStore = useAppsStore()
const { getUserInfo: userInfo } = storeToRefs(useStore)
const ConfirmDia = defineAsyncComponent(
  () => import('@/components/ConfirmDia.vue')
)
const toast = useMessage()
const $clone = inject('$clone') as <T>(data: T) => T

const { width } = useWindowSize()
const avatarSize = computed(() => {
  const bili = width.value / 1920
  return Number((56 * bili).toFixed(2))
})

const confirmRef = ref()
let oldId = 0
const tips = ref('确定要关注此用户吗？')
const handCancel = (e: any) => {
  if (e.follow_id === userInfo.value.id) {
    toast.error('不能关注自己')
    return
  }
  oldId = e.follow_id
  if (e.isFollow) {
    tips.value = '确定取消关注吗？'
  } else {
    tips.value = '确定要关注此用户吗？'
  }
  confirmRef.value.open()
}
const handConfirm = async () => {
  const info = tableData.value.find((el: any) => el.follow_id === oldId)
  if (info.isFollow) {
    await followApi.cancel({
      userid: oldId
    })
    toast.success('取关成功')
  } else {
    const { data } = await followApi.add({
      userid: oldId
    })
    info.isByFansConcern = data
    toast.success('关注成功')
  }
  const index = tableData.value.findIndex((el: any) => el.follow_id === oldId)
  info.isFollow = !info.isFollow
  tableData.value.splice(index, 1, info)
  emit('change')
}

const router: any = useRouter()
const handDetail = (e: any) => {
  const href = router.resolve({
    path: '/userPage',
    query: {
      id: e.follow_id
    }
  })
  window.open(href.href, '_blank')
}
const handContentDetail = (e: any) => {
  const href = router.resolve({
    path: e.book_type === 1 ? '/mhdetail' : '/detail',
    query: {
      id: e.id
    }
  })
  window.open(href.href, '_blank')
}

/**
 *  列表
 * */
const queryForm = ref({
  current: 1,
  size: 10,
  userId: props.userId
})
const tableData: any = ref([])
let loading = false
let finish = ref(false)
const onReset = () => {
  tableData.value = []
  queryForm.value.current = 1
  finish.value = false
  loading = false
  loadMore()
}

const loadMore = async () => {
  if (finish.value) return
  if (loading) return
  loading = true
  const params = $clone(queryForm.value)
  const { data } = await homeApi.follow(params)
  if (params.current === 1) {
    tableData.value = data.data
  } else {
    tableData.value = [...tableData.value, ...data.data]
  }
  if (data.data.length < queryForm.value.size) {
    finish.value = true
  }
  queryForm.value.current++
  loading = false
}

const pageRef = ref<HTMLElement | undefined>(undefined)
const handleScroll = () => {
  const container: HTMLElement | undefined = pageRef.value
  if (!container) return
  if (container.scrollTop + container.clientHeight > container.scrollHeight) {
    loadMore()
  }
}

onMounted(() => {
  onReset()
})
</script>
<style scoped lang="scss">
.follow-list {
  margin-top: 20px;
  flex: 1 0 0;
  overflow-y: auto;
  .empty {
    padding-top: 120px;
  }
  .cell {
    display: flex;
    gap: 20px;
    &:not(:first-child) {
      margin-top: 32px;
    }
    .user-card {
      width: 316px;
      height: 234px;
      background: #f5f5f5;
      border-radius: 10px;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      .name {
        margin-top: 8px;
        font-size: 16px;
        font-family: PingFang SC, PingFang SC;
        font-weight: bold;
        color: #333333;
      }
      .desc {
        margin-top: 8px;
        font-size: 12px;
        font-family: PingFang SC, PingFang SC;
        font-weight: 400;
        color: #999999;
      }
      .more {
        margin-top: 12px;
        font-size: 14px;
        font-family: PingFang SC, PingFang SC;
        font-weight: 400;
        color: #333333;
        display: flex;
        span {
          display: block;
          padding: 0 12px;
          position: relative;
          &:first-child {
            &:before {
              content: '';
              position: absolute;
              width: 0;
              height: 10px;
              right: 0;
              top: 50%;
              transform: translateY(-50%);
              border: 1px solid #999;
            }
          }
        }
      }
      .btn {
        margin-top: 20px;
        width: 92px;
        height: 34px;
        border-radius: 6px;
        font-size: 14px;
      }
      .follw-btn {
        margin-top: 20px;
        width: 92px;
        height: 34px;
        background: #ffffff;
        border-radius: 6px;
        font-size: 14px;
      }
    }
    .hor-img {
      width: 210px;
      aspect-ratio: 4/4;
      border-radius: 10px;
      object-fit: cover;
      cursor: pointer;
      -webkit-user-drag: none;
      display: block;
    }
  }
}
</style>
